package jdbc.dao_.dao;

import jdbc.dao_.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 开发BasicDAO,是其他DAO的父类
 */
public class BasicDAO<T> {  //泛型指定具体类型

    QueryRunner qr = new QueryRunner();

    //通用dml方法，针对任意的表
    public int update(String sql, Object... params) {

        Connection conn = null;
        try {
            conn = JDBCUtilsByDruid.getConnection();
            return qr.update(conn, sql, params);
        } catch (SQLException e) {
            //将编译异常转换成运行异常，抛出去
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            JDBCUtilsByDruid.close(conn, null, null);
        }
    }

    /**
     *
     * @param sql sql语句
     * @param clazz 传入一个类的Class对象 比如 Actor.class
     * @param params  传入?的具体值，可以是多个
     * @return 根据 Actor.class 返回对应的 ArrayList集合
     */
    //返回多个对象(即查询的结果是多行)，针对任意表
    public List<T> queryMulti(String sql, Class<T> clazz, Object... params) {

        Connection conn = null;
        try {
            conn = JDBCUtilsByDruid.getConnection();
            return qr.query(conn, sql, new BeanListHandler<T>(clazz), params);
        } catch (SQLException e) {
            //将编译异常转换成运行异常，抛出去
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            JDBCUtilsByDruid.close(conn, null, null);
        }

    }

    //查询单行结果的通用方法
    public T querySingle(String sql, Class<T> clazz, Object... params) {

        Connection conn = null;
        try {
            conn = JDBCUtilsByDruid.getConnection();
            return qr.query(conn, sql, new BeanHandler<T>(clazz), params);
        } catch (SQLException e) {
            //将编译异常转换成运行异常，抛出去
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            JDBCUtilsByDruid.close(conn, null, null);
        }
    }

    //返回单值的方法
    public Object queryScalar(String sql, Object... params) {

        Connection conn = null;
        try {
            conn = JDBCUtilsByDruid.getConnection();
            return qr.query(conn, sql, new ScalarHandler<>(), params);
        } catch (SQLException e) {
            //将编译异常转换成运行异常，抛出去
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            JDBCUtilsByDruid.close(conn, null, null);
        }
    }

}
